<template>
  <van-search
    v-model="value"
    :show-action="showAction"
    placeholder="请输入搜索关键词"
    @search="onSearch"
    @cancel="onCancel"
    @focus="onFocus"
  />
  <van-row v-show="!showAction">
    <van-col span="8" offset="1">
      <van-cell title="热搜榜" label="大家都在看" />
    </van-col>
  </van-row>

  <van-cell-group inset border v-show="!showAction">
    <van-list
      class="list"
      v-model="loading"
      :finished="finished"
      loading-text="加载中..."
      finished-text="没有更多了"
      offset="10"
      @load="onLoad"
    >
      <van-cell
        v-for="post in list"
        :title="post.index"
        :key="post.id"
        :value="post.content"
        @click="OnClickPost(post)"
      >
      </van-cell>
    </van-list>
  </van-cell-group>

  <van-list
    v-show="showAction"
    class="list"
    v-model="loadingPost"
    :finished="finishedPost"
    loading-text="加载中..."
    finished-text="没有更多了"
    offset="10"
  >
    <van-back-top style="color: white" right="3vw" bottom="12vh" />
    <van-cell-group>
      <van-cell v-for="post in listPost" :key="post.id">
        <van-row class="van-rowstyle">
          <van-col>
            <van-image
              round
              fit="cover"
              :src="post.useravatar"
              width="2rem"
              height="2rem"
            />
          </van-col>
          <van-col offset="1">
            <van-text-ellipsis
              class="usernamestyle"
              rows="8"
              :content="post.username"
            />
          </van-col>
          <van-col offset="1">
            <van-tag
              v-if="post.userrole === 'admin'"
              plain
              type="primary"
              color="#808080"
              round
              >管理员
            </van-tag>
          </van-col>
          <van-col offset="1">
            <van-tag
              v-if="post.isTop == 1"
              round
              plain
              type="primary"
              color="#808080"
              >置顶
            </van-tag>
          </van-col>
        </van-row>
        <van-row class="van-rowstyle" @click="OnClickPost(post)">
          <van-col offset="3">
            <van-text-ellipsis
              class="ellstyle"
              rows="50"
              :content="post.content"
            />
          </van-col>
        </van-row>
        <van-row
          justify="space"
          @click="OnClickPost(post)"
          class="van-rowstyle"
        >
          <van-col offset="3" v-for="img in post.imagepath" :key="img">
            <van-image :src="img" fit="cover" width="6.5rem" height="6.5rem">
              <template v-slot:error>加载失败</template>
            </van-image>
          </van-col>
        </van-row>
        <van-row justify="space-between" class="van-rowstyle">
          <van-col class="tagstyle" span="6" offset="1">
            #{{ post.tag }}
          </van-col>
          <van-col span="6" offset="1">
            {{ post.createTime }}
          </van-col>
          <van-col span="6" offset="1"> {{ post.seeNum }}人围观</van-col>
        </van-row>
      </van-cell>
    </van-cell-group>
  </van-list>

  <van-tabbar v-model="activeName" @change="OnchangeTab">
    <van-tabbar-item name="" icon="wap-home-o" to="">主页</van-tabbar-item>
    <van-tabbar-item name="search" icon="search">搜索</van-tabbar-item>
    <van-tabbar-item name="putout" icon="add">发布</van-tabbar-item>
    <van-tabbar-item name="user" icon="user-o">个人中心</van-tabbar-item>
  </van-tabbar>
</template>

<script>
import router from "@/router";
import { ref } from "vue";
import MyAxios from "@/plugins/MyAxios";
import content from "vant-green/lib/tabs/Content";
import store from "@/store";

export default {
  setup() {
    const backPath = ref(store.state.backedPath);
    window.scrollTo(0, store.state.SearchScrollY);

    const activeName = ref("search");
    const value = ref("");
    const showAction = ref(false);
    showAction.value = store.state.SearchShowAction;
    const loadingPost = ref(false);
    const finishedPost = ref(false);
    const listPost = ref([]);
    const page = ref(1);
    const totalPages = ref(0); // 最多有多少页
    const onSearch = () => {
      loadingPost.value = true;
      finishedPost.value = false;
      page.value = 1;
      totalPages.value = 0;
      listPost.value = [];
      store.state.SearchPostList = [];
      store.state.SearchPageNumber = 1;
      if (value.value === "") return;
      onLoadPost();
    };
    const onFocus = () => {
      showAction.value = true;
    };
    const onCancel = () => {
      showAction.value = false;
    };
    const OnchangeTab = (name) => {
      router.push({
        path: `/${name}`, // 假设你的路由路径是 /home, /about 这样的
        query: { name: name }, // query 参数应该是一个对象
      });
    };

    const list = ref([]);
    const loading = ref(false);
    const finished = ref(false);

    const onLoad = () => {
      if (finished.value) return;
      loading.value = true; // 设置正在加载状态

      MyAxios.get("/post/getTopTenPosts").then((res) => {
        for (let i = 0; i < res.data.length; i++) {
          const index = i + 1;
          const { content, id } = res.data[i];
          list.value.push({ content, id, index });
        }
      });
      loading.value = false; // 无论成功或失败，都设置加载状态为false
      finished.value = true; // 设置加载完成
    };

    /**
     * 计算时间差
     * @param timeString
     * @returns {*}
     */
    const formatTimeDifference = (timeString) => {
      const now = new Date();
      const createTime = new Date(timeString);
      const diff = now - createTime;
      let result;

      if (diff < 0) {
        result = "未来时间";
      } else if (diff < 1000 * 60) {
        // 小于1分钟
        result = `${Math.floor(diff / 1000)} 秒前`;
      } else if (diff < 1000 * 60 * 60) {
        // 小于1小时
        result = `${Math.floor(diff / (1000 * 60))} 分钟前`;
      } else if (diff < 1000 * 60 * 60 * 24) {
        // 小于1天
        result = `${Math.floor(diff / (1000 * 60 * 60))} 小时前`;
      } else {
        const days = Math.floor(diff / (1000 * 60 * 60 * 24));
        result = `${days} 天前`;
      }

      return result;
    };

    const getUser = (id) => {
      const res = MyAxios.get("/user/get/vo", {
        params: {
          id: id,
        },
      });
      return res;
    };

    const onLoadPost = () => {
      page.value = store.state.SearchPageNumber;
      listPost.value = store.state.SearchPostList;
      if (finishedPost.value) return;
      loadingPost.value = true; // 设置正在加载状态
      MyAxios.post("/post/search/page/vo", {
        content: value.value,
        current: page.value,
        pageSize: 10,
      }).then((res) => {
        const { code, data } = res;
        totalPages.value = data.pages;
        for (let i = 0; i < data.records.length; i++) {
          const {
            anon,
            anon_name,
            content,
            createTime,
            id,
            tags,
            imgpath,
            userId,
            seeNum,
          } = data.records[i];

          let useravatar = ref("");
          let username = ref("");
          let userrole = ref("");

          getUser(userId).then((res) => {
            const { userAvatar, userName, userRole } = res.data;

            if (userAvatar === null || anon === 1) {
              useravatar.value = store.state.anonImg;
            } else {
              useravatar.value =
                "http://" + backPath.value + "/api/userimages/" + userAvatar;
            }
            if (anon === 1) {
              username.value = anon_name;
            } else {
              username.value = userName;
            }
            if (userRole !== null) {
              userrole.value = userRole;
            }
          });
          const arr = JSON.parse(tags);

          const tag = arr[0];

          const formattedCreateTime = formatTimeDifference(createTime);

          let imagePaths = ref([]); // 更改为更具描述性的变量名
          try {
            imagePaths.value = JSON.parse(imgpath); // 直接解析到响应式引用的value中
          } catch (error) {
            console.error("Parsing imgpath failed:", error); // 添加错误处理
          }

          if (imagePaths.value != null) {
            for (let i = 0; i < imagePaths.value.length; i++) {
              // 使用模板字符串优化URL拼接
              imagePaths.value[
                i
              ] = `http://${backPath.value}/api/postimages/${imagePaths.value[i]}`;
            }
          }

          // const createtimeFiter = createtime.match(/^\d{4}-\d{2}-\d{2}/)[0];
          listPost.value.push({
            anon,
            anon_name,
            content,
            createTime: formattedCreateTime,
            id,
            tag,
            seeNum,
            useravatar,
            username,
            imagepath: imagePaths.value,
            showPopover: false,
            isTop: 1,
            userrole,
          });
        }
        page.value++;
        store.state.SearchPageNumber = page;
        store.state.SearchPostList = listPost;
        if (page.value > totalPages.value) {
          loadingPost.value = false; // 无论成功或失败，都设置加载状态为false
          finishedPost.value = true; // 设置加载完成
          return;
        }
      });
    };

    const OnClickPost = (post) => {
      store.state.SearchScrollY = window.scrollY;
      store.state.SearchShowAction = showAction.value;
      router.push({
        path: "/post", // 假设你的路由路径是 /home, /about 这样的
        query: { id: post.id },
      });
    };
    return {
      activeName,
      value,
      showAction,
      onSearch,
      onFocus,
      onCancel,
      OnchangeTab,
      onLoad,
      list,
      loading,
      finished,
      OnClickPost,
      onLoadPost,
      loadingPost,
      finishedPost,
      listPost,
    };
  },
};
</script>

<style scoped>
.ellstyle {
  /* 调整字体大小 */
  font-size: 16px; /* 或者您想要的任何大小 */

  color: black;
  text-align: left;
  line-height: 1.6;
  /* 调整字体类型 */
  font-family: Arial, sans-serif; /* 或者您喜欢的任何字体 */
}

.usernamestyle {
  font-size: 15px;
  line-height: 1.5;
  color: #394968;
}

.tagstyle {
  font-size: 15px;
  color: #00388b;
}
/* 调整行之间的间距 */
.van-rowstyle {
  margin-bottom: 5px; /* 在每行下方添加间距 */
}
</style>
